package org.springblade.common.security.service;

import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springblade.common.constant.SecurityConstants;
import org.springblade.common.security.util.UserDetailUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.system.user.entity.User;
import org.springblade.system.user.entity.UserInfo;
import org.springblade.system.user.feign.IUserClient;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * @File: CsjUserDetailsService.java
 * @Project: csjbot-service
 * @Package: org.springblade.auth.service
 * @Description:
 * @Company: 苏州穿山甲机器人股份有限公司
 * @author: zhouhong
 * @date: 2019年11月21 13时51分
 * @version: V1.0.0
 */
@Slf4j
@Service
@AllArgsConstructor
public class CsjUserDetailsService implements UserDetailsService {
	private final IUserClient userClient;
	private final CacheManager cacheManager;

	/**
	 * 用户密码登录
	 *
	 * @param username 用户名
	 * @return
	 */
	@Override
	@SneakyThrows
	public UserDetails loadUserByUsername(String username) {
		Cache cache = cacheManager.getCache("user_details");
		if (cache != null && cache.get(username) != null) {
			return (UserDetails) cache.get(username).get();
		}

		R<UserInfo> result = userClient.userInfo(null, username);
		UserDetails userDetails = UserDetailUtil.getUserDetails(result);
		cache.put(username, userDetails);
		return userDetails;
	}
}
